<script setup>
import { computed, ref } from 'vue';
import { Icon } from '@iconify/vue';
import { useProblemsStore } from '../../stores/problems';
import { useEditorStore } from '../../stores/editor';
import { openContextMenu } from '../../assets/menus';
import { useI18n } from 'vue-i18n';

const emit = defineEmits(['navigate']);
const problems = useProblemsStore();
const editor = useEditorStore();
const { t } = useI18n();

const activeFileOnly = ref(false);
const expandedFiles = ref(new Set());

const search = computed({
  get: () => problems.searchText,
  set: (v) => problems.setSearchText(v),
});

const showError = computed(() => problems.severityFilter.has('error'));
const showWarning = computed(() => problems.severityFilter.has('warning'));
const showInfo = computed(() => problems.severityFilter.has('info'));

// Problem counts for toolbar display
const errorCount = computed(() => problems.items.filter(p => p.severity === 'error').length);
const warningCount = computed(() => problems.items.filter(p => p.severity === 'warning').length);
const infoCount = computed(() => problems.items.filter(p => p.severity === 'info').length);

// Filtered items (with optional active file filter)
const filteredItems = computed(() => {
  let items = problems.filteredItems;
  if (activeFileOnly.value && editor.activeFile?.path) {
    items = items.filter(item => item.file === editor.activeFile.path);
  }
  return items;
});

function toggle(sev) { 
  problems.toggleSeverity(sev); 
}

function toggleActiveFileOnly() {
  activeFileOnly.value = !activeFileOnly.value;
}

const grouped = computed(() => {
  const map = new Map();
  for (const it of filteredItems.value) {
    const key = it.file || '(unknown)';
    if (!map.has(key)) map.set(key, []);
    map.get(key).push(it);
  }
  return Array.from(map.entries());
});

function toggleFileExpanded(file) {
  if (expandedFiles.value.has(file)) {
    expandedFiles.value.delete(file);
  } else {
    expandedFiles.value.add(file);
  }
}

function open(item) {
  problems.setSelected(item?.id || null);
  emit('navigate', item);
}

function next() {
  const it = problems.navigateNext();
  if (it) emit('navigate', it);
}
function prev() {
  const it = problems.navigatePrev();
  if (it) emit('navigate', it);
}

function onProblemContextMenu(evt, p) {
  try {
    evt.preventDefault();
    evt.stopPropagation();
    problems.setSelected(p?.id || null);
    const at = { x: evt.clientX, y: evt.clientY };
    openContextMenu({ use: 'problems.item.context' }, at, { problem: p, t });
  } catch {}
}

// VS Code-like severity icons and colors
function getSeverityIcon(severity) {
  switch (severity) {
    case 'error': return 'codicon:error';
    case 'warning': return 'codicon:warning';
    case 'info': return 'codicon:info';
    default: return 'codicon:circle-outline';
  }
}

function getSeverityColor(severity) {
  switch (severity) {
    case 'error': return 'text-red-500';
    case 'warning': return 'text-amber-500';
    case 'info': return 'text-blue-500';
    default: return 'text-slate-500';
  }
}
</script>

<template>
  <div class="text-[12px] select-text h-full flex flex-col">
    <!-- VS Code-style toolbar -->
    <div class="flex items-center justify-between px-1 py-1 border-b border-panel-border">
      <!-- Left: Filter toggles with counts -->
      <div class="flex items-center gap-1">
        <button 
          class="inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] hover:bg-subtle-bg transition-colors"
          :class="showError ? 'bg-subtle-bg' : ''"
          @click="toggle('error')"
          :title="`Toggle Error Problems (${errorCount})`"
        >
          <Icon icon="codicon:error" width="12" height="12" class="text-red-500" />
          <span>{{ errorCount }}</span>
        </button>
        
        <button 
          class="inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] hover:bg-subtle-bg transition-colors"
          :class="showWarning ? 'bg-subtle-bg' : ''"
          @click="toggle('warning')"
          :title="`Toggle Warning Problems (${warningCount})`"
        >
          <Icon icon="codicon:warning" width="12" height="12" class="text-amber-500" />
          <span>{{ warningCount }}</span>
        </button>
        
        <button 
          class="inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] hover:bg-subtle-bg transition-colors"
          :class="showInfo ? 'bg-subtle-bg' : ''"
          @click="toggle('info')"
          :title="`Toggle Info Problems (${infoCount})`"
        >
          <Icon icon="codicon:info" width="12" height="12" class="text-blue-500" />
          <span>{{ infoCount }}</span>
        </button>

        <div class="w-px h-4 bg-panel-border mx-1"></div>

        <!-- Active File Only Toggle -->
        <button 
          class="inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] hover:bg-subtle-bg transition-colors"
          :class="activeFileOnly ? 'bg-subtle-bg' : ''"
          @click="toggleActiveFileOnly"
          :title="activeFileOnly ? 'Show All Files' : 'Show Active File Only'"
        >
          <Icon icon="codicon:filter" width="12" height="12" />
          <span v-if="activeFileOnly">Active File Only</span>
        </button>
      </div>

      <!-- Right: Search and navigation -->
      <div class="flex items-center gap-1">
        <div class="relative">
          <input 
            type="text" 
            placeholder="Filter (e.g. text, **/*.ts, !**/node_modules/**)" 
            v-model="search" 
            class="w-64 px-2 py-1 text-[11px] rounded border border-panel-border bg-panel-bg outline-none focus:border-blue-500 dark:focus:border-blue-400" 
          />
          <Icon 
            v-if="search" 
            icon="codicon:close" 
            width="12" 
            height="12" 
            class="absolute right-2 top-1/2 -translate-y-1/2 cursor-pointer text-muted-fg hover:text-panel-fg"
            @click="search = ''"
          />
        </div>
        
        <div class="w-px h-4 bg-panel-border mx-1"></div>
        
        <button 
          class="p-1 rounded hover:bg-subtle-bg transition-colors"
          @click="prev"
          :disabled="!filteredItems.length"
          title="Go to Previous Problem"
        >
          <Icon icon="codicon:chevron-up" width="12" height="12" />
        </button>
        <button 
          class="p-1 rounded hover:bg-subtle-bg transition-colors"
          @click="next"
          :disabled="!filteredItems.length"
          title="Go to Next Problem"
        >
          <Icon icon="codicon:chevron-down" width="12" height="12" />
        </button>
      </div>
    </div>

    <!-- VS Code-style problem list -->
    <div class="flex-1 min-h-0 overflow-auto thin-scrollbar scrollbar-compact scrollbar-track">
      <div v-if="!filteredItems.length" class="flex flex-col items-center justify-center h-32 text-muted-fg">
        <Icon icon="codicon:pass" width="24" height="24" class="mb-2" />
        <div class="text-sm">
          <span v-if="problems.items.length === 0">No problems have been detected in the workspace.</span>
          <span v-else-if="activeFileOnly && !editor.activeFile">No active editor</span>
          <span v-else-if="search">No problems match your filter.</span>
          <span v-else>No problems to show with the current filters.</span>
        </div>
      </div>
      <div v-else class="px-1 py-1">
        <div v-for="([file, items], idx) in grouped" :key="String(file)+':'+idx" class="mb-1">
          <!-- File header with expand/collapse -->
          <div 
            class="flex items-center gap-1 px-1 py-1 hover:bg-subtle-bg cursor-pointer rounded text-[11px] font-medium"
            @click="toggleFileExpanded(file)"
          >
            <Icon 
              :icon="expandedFiles.has(file) ? 'codicon:chevron-down' : 'codicon:chevron-right'" 
              width="12" 
              height="12" 
              class="text-muted-fg" 
            />
            <Icon icon="codicon:file" width="12" height="12" class="text-muted-fg" />
            <span class="truncate flex-1">{{ file }}</span>
            <span class="text-muted-fg text-[10px]">{{ items.length }}</span>
          </div>

          <!-- Problem items (when expanded) -->
          <div v-show="!expandedFiles.has(file) || expandedFiles.has(file)" class="ml-4">
            <div 
              v-for="p in items" 
              :key="p.id" 
              class="flex items-center gap-2 px-1 py-0.5 hover:bg-subtle-bg cursor-pointer rounded text-[11px]"
              :class="problems.selectedId === p.id ? 'bg-blue-50 dark:bg-blue-900/20 border-l-2 border-blue-500' : ''"
              @click="open(p)"
              @contextmenu="onProblemContextMenu($event, p)"
            >
              <Icon 
                :icon="getSeverityIcon(p.severity)" 
                width="12" 
                height="12" 
                :class="getSeverityColor(p.severity)" 
              />
              <span class="flex-1 truncate">{{ p.message }}</span>
              <span class="text-muted-fg text-[10px] font-mono">
                [{{ p.line || 1 }}, {{ p.column || 1 }}]
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


